package com.vehiclemanagement.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vehiclemanagement.entity.VehicleUseRecord;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 车辆出车记录Mapper接口
 */
@Mapper
public interface VehicleUseRecordMapper extends BaseMapper<VehicleUseRecord> {
    
    /**
     * 自定义分页查询，带车辆和驾驶员信息
     * 
     * @param page 分页对象
     * @param whereSql 自定义WHERE条件SQL（不包含WHERE关键字）
     * @return 分页结果
     */
    @Select("SELECT r.*, v.plate_number, d.name as driver_name FROM vehicle_use_record r " +
            "LEFT JOIN vehicle v ON r.vehicle_id = v.id " +
            "LEFT JOIN driver d ON r.driver_id = d.id " +
            "WHERE ${whereSql}")
    IPage<VehicleUseRecord> selectPageWithInfo(Page<VehicleUseRecord> page, @Param("whereSql") String whereSql);
    
    /**
     * 查询车辆是否有未归还的出车记录
     * 
     * @param vehicleId 车辆ID
     * @return 记录数
     */
    @Select("SELECT COUNT(*) FROM vehicle_use_record WHERE vehicle_id = #{vehicleId} " +
            "AND status IN (1, 2) AND del_flag = 0")
    int countActiveUseByVehicleId(@Param("vehicleId") Long vehicleId);
    
    /**
     * 查询驾驶员是否有未归还的出车记录
     * 
     * @param driverId 驾驶员ID
     * @return 记录数
     */
    @Select("SELECT COUNT(*) FROM vehicle_use_record WHERE driver_id = #{driverId} " +
            "AND status IN (1, 2) AND del_flag = 0")
    int countActiveUseByDriverId(@Param("driverId") Long driverId);
    
    /**
     * 更新车辆归还信息
     * 
     * @param id 出车记录ID
     * @param actualEndTime 实际归还时间
     * @param endMileage 归还里程数
     * @param updateTime 更新时间
     * @return 影响行数
     */
    @Update("UPDATE vehicle_use_record SET actual_end_time = #{actualEndTime}, " +
            "end_mileage = #{endMileage}, status = 3, update_time = #{updateTime} " +
            "WHERE id = #{id} AND del_flag = 0")
    int updateReturnInfo(@Param("id") Long id, @Param("actualEndTime") LocalDateTime actualEndTime,
                        @Param("endMileage") Double endMileage, @Param("updateTime") LocalDateTime updateTime);
    
    /**
     * 物理删除出车记录
     * 
     * @param id 出车记录ID
     * @return 影响行数
     */
    @Delete("DELETE FROM vehicle_use_record WHERE id = #{id}")
    int deletePhysically(@Param("id") Long id);
} 